package com.tccmeta.matchmaker.wxSdk;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

public class Sign {
    /**
     * jsSdk 获取微信config
     *
     * @param url
     * @return
     */
    public static JsSdk sign(String url,String appId,String ticket) {
        JsSdk jsSdk = new JsSdk();
        jsSdk.setAppid(appId);
        jsSdk.setUrl(url);
        String nonce_str = create_nonce_str();
        jsSdk.setNoncestr(nonce_str);
        String timestamp = create_timestamp();
        jsSdk.setTimestamp(timestamp);
        String signature = "";
        //注意这里参数名必须全部小写，且必须有序
        String string1 = "jsapi_ticket=" + ticket +
                "&noncestr=" + nonce_str +
                "×tamp=" + timestamp +
                "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            jsSdk.setSignature(signature);
        } catch (NoSuchAlgorithmException e) {
            jsSdk = null;
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            jsSdk = null;
            e.printStackTrace();
        }
        return jsSdk;
    }

    /**
     * 生成随机数
     *
     * @return
     */
    private static String create_nonce_str() {
        return UUID.randomUUID().toString().substring(0, 20);
    }

    /**
     * 当前日期字符串生成
     *
     * @return
     */
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     *
     * @param hash
     * @return
     */
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}